<?php
/**
 * @author Jumper Swordwave
 * date: 2021/04/19
 */
declare(strict_types=1);
namespace App\Game\Commands;

use Psr\Container\ContainerInterface;
use App\Constants\ErrorCode;
use App\Game\Service\{UserService, RoomService};
use App\Game\Core\{Request, Response};
use App\Game\Task\ChatTask;

/**
 * 聊天室
 */
class ChatCommand
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @var UserService
     */
    private $userService;

    /**
     * @var RoomService
     */
    private $roomService;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->userService = $container->get(UserService::class);
        $this->roomService = $container->get(RoomService::class);
    }

    /**
     * 用户发言
     */
    public function chat(Request $req)
    {
        $user = $this->userService->findUser($req->getFd(), $req->getUser());
        if ($user == null) {
            return Response::error(ErrorCode::USER_ERROR, '用户异常，请先登陆');
        }

        $content = $req->input('content');
        $room = $this->roomService->findRoom($user->room);
        if ($room != null) {
            $task = $this->container->get(ChatTask::class);
            $task->broadcast($room, $user, $content);
        }

        return null;
    }
}